package xworker.httpclient.tools;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.util.EntityUtils;
import org.xmeta.ActionContext;
import org.xmeta.util.ExceptionUtil;
import org.xmeta.util.UtilString;
import xworker.httpclient.HttpClientManager;
import xworker.lang.util.UtilTemplate;

import java.io.IOException;
import java.util.*;

public class HttpClientExecutor {
    HttpUriRequest request;
    StringBuilder requestHeaders;
    HttpResponse httpResponse = null;
    ActionContext actionContext = new ActionContext();
    String responseContent;


    public HttpClientExecutor(HttpUriRequest request){
        this.request = request;
    }

    public String getGeneralMessage(){
        StringBuilder sb = new StringBuilder();
        sb.append("<pre>\n");
        sb.append("<b>").append(getLabel("lang:d=常规&en=General")).append("</b>\n");
        sb.append("&nbsp;&nbsp;<b>").append(getLabel("lang:d=请求 URL：&en=Request URL: ")).append("</b>").append(request.getURI()).append("\n");
        sb.append("&nbsp;&nbsp;<b>").append(getLabel("lang:d=请求方法：&en=Request Method: ")).append("</b>").append(request.getMethod()).append("\n");
        if(httpResponse != null){
            sb.append("&nbsp;&nbsp;<b>").append(getLabel("lang:d=状态代码：&en=Status Code: ")).append("</b>").append(httpResponse.getStatusLine().getStatusCode()).append("\n");
        }
        sb.append("\n<b>").append(getLabel("lang:d=请求头&en=Request Headers")).append("</b>\n");
        sb.append( headersToStringBuilder(request.getAllHeaders()));

        sb.append("\n<b>").append(getLabel("lang:d=响应头&en=Response Headers")).append("</b>\n");
        sb.append(getResponseHeaders());
        sb.append("</pre>");
        return sb.toString();
    }

    public String getResponsePreview(){
        return responseContent == null ? "" : responseContent;
    }

    public String getResponseCode(){
        StringBuilder sb = new StringBuilder();
        sb.append("<pre>\n");
        if(responseContent != null){
            Map<String, Object> data = new HashMap<>();
            data.put("data", responseContent);
            try {
                sb.append(UtilTemplate.processString(data, "${data?html}"));
            }catch(Exception e){
                sb.append(ExceptionUtil.toString(e));
            }
        }
        sb.append("</pre>\n");

        return sb.toString();
    }

    public String getResponseContent(){
        return responseContent;
    }

    private String getLabel(String label){
        return UtilString.getString(label, actionContext);
    }

    private StringBuilder getResponseHeaders(){
        if(httpResponse != null){
            return headersToStringBuilder(httpResponse.getAllHeaders());
        }else{
            return new StringBuilder();
        }
    }

    private StringBuilder headersToStringBuilder(Header[] headers){
        List<Header> headerList = new ArrayList<>(Arrays.asList(headers));

        headerList.sort(Comparator.comparing(Header::getName));

        StringBuilder builder = new StringBuilder();
        for(Header header : headerList){
            builder.append("&nbsp;&nbsp;<b>").append(header.getName()).append(": </b>").append(header.getValue()).append("\n");
        }

        return builder;
    }

    public void execute(){
        HttpClient httpClient = HttpClientManager.getDefaultHttpClient();

        HttpEntity entity = null;
        try{
            httpResponse = httpClient.execute(request);
            entity = httpResponse.getEntity();

            responseContent = EntityUtils.toString(entity, "utf-8");
        }catch(Exception e){
            responseContent = ExceptionUtil.toString(e);
        }finally{
            if(entity != null){
                try {
                    EntityUtils.consume(entity);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
